package com.koron.operation.dispatch.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.koron.bean.base.Response;
import com.koron.bean.query.OrderItem;
import com.koron.bean.system.staff.vo.EamUser;
import com.koron.common.core.business.configsettings.bean.ConfigDetailQuery;
import com.koron.common.core.business.configsettings.mapper.ConfigTypeMapper;
import com.koron.common.core.config.ThreadLocalContext;
import com.koron.common.core.util.CodeTools;
import com.koron.common.core.util.FastJsonUtils;
import com.koron.common.core.util.StringUtils;
import com.koron.operation.dispatch.bean.*;
import com.koron.operation.dispatch.bean.dto.*;
import com.koron.operation.dispatch.bean.vo.LineCockpitVo;
import com.koron.operation.dispatch.enums.EquipmentEnum;
import com.koron.operation.dispatch.enums.OverhaulStatusEnum;
import com.koron.operation.dispatch.feign.DeviceFeign;
import com.koron.operation.dispatch.feign.MonitorFeign;
import com.koron.operation.dispatch.mapper.AffectedLineMapper;
import com.koron.operation.dispatch.mapper.EquipmentAccidentMapper;
import com.koron.operation.dispatch.mapper.EquipmentDeMapper;
import com.koron.operation.dispatch.mapper.EquipmentHistoryMapper;
import com.koron.operation.dispatch.service.EquipmentRunService;
import com.koron.operation.startlog.bean.StartLogBean;
import com.koron.operation.startlog.services.StartLogService;
import com.koron.operation.util.StarLogUntil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.koron.ebs.mybatis.ADOConnection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.function.Predicate;
import java.util.stream.Collectors;

@Slf4j
@RequestMapping("/equipment")
@RestController
@Api(tags = "调度管理")
public class EquipmentDeController {

    private String getCurrDs() {
        return ThreadLocalContext.get().getCurrDs();
    }

    private EamUser getCurrUser() {
        return ThreadLocalContext.get();
    }

    @Autowired
    private EquipmentRunService equipmentrunservice;

    @Autowired
    DeviceFeign deviceservice;

    @Autowired
    private MonitorFeign monitorfeign;

    @Autowired
    private StartLogService startlogservice;


    private static Map<String, String> typemap = new HashMap();

    // 根据异步操作数设置线程
    private ExecutorService threadPool = Executors.newFixedThreadPool(3);

    private CountDownLatch latch;

    //因为设备台账没有设计对应的 类型 code
    static {
        typemap.put("主变", EquipmentEnum.TRAN.getValue());
        typemap.put("线路", EquipmentEnum.LINE.getValue());
        typemap.put("机组", EquipmentEnum.UNIT.getValue());
    }


        @ApiOperation(value = "同步")
    @GetMapping("/synchroEquipmeng")
    public Response<String> synchroEquipmeng() {
        EamUser eamUser = ThreadLocalContext.get();
        long start = System.currentTimeMillis();
        //因为设备台账没有设计对应的 类型 code
//        ArrayList<String> arrayList = CollectionUtil.newArrayList("主变", "线路", "机组");//同步类型
//        ArrayList<String> arrayList = CollectionUtil.newArrayList("TRAN", "LINE", "UNIT");//同步类型
        Map<String, String> dictByClassCode = CodeTools.getDictByClassCode("operationManagement", "dispatch_type");
        Set<String> keyset = dictByClassCode.keySet();
        // 倒计时数为异步线程数
        latch = new CountDownLatch(keyset.size());

        Map<String, String> errType = new HashMap<>();  //同步发生的错误信息
        List<EquipmentBean> synlist = new ArrayList<>();//同步数据
        // 异步返回结果
        List<Future<List<EquipmentBean>>> futures = new ArrayList<>();
        keyset.stream().forEach(a -> {
            // 遍历需要异步的请求，并提交至线程池
            Future<List<EquipmentBean>> submit = threadPool.submit(() -> {
                ThreadLocalContext.set(eamUser);
                List<EquipmentBean> equipments = getEquipments(a);

                return equipments;
            });
            futures.add(submit);
        });
        try {
            // 等待本地提交的异步操作完成
            latch.await();
        } catch (Exception e) {
            log.info(e.getMessage());
        }
        // 遍历异步返回的结果，并江结果放入集合中
        futures.stream().forEach(future -> {
            try {
                synlist.addAll(future.get());
            } catch (Exception e) {
                log.info(e.getMessage());
            }
        });
        if (StringUtils.isNotEmpty(errType)) {
            Set<String> keySet = errType.keySet();
            return Response.fail(errType.get((keySet.iterator().next())));//返回调用同步接口错误信息
        }

        if (StringUtils.isNotEmpty(synlist)) {
            String result = ADOConnection.runTask(getCurrDs(), equipmentrunservice, "saveOrUpdate", String.class, synlist);
            return Response.success(result);
        }
        return Response.ok("没有要同步的设备，请到台账变更中维护的主要设备信息");
    }


    @ApiOperation(value = "基础信息维护-列表")
    @GetMapping("/queryBaseListNoPage")
    public Response<List<EquipmentBean>> queryBaseListNoPage(EquipmentDto dto) {
//        return Response.ok(new PageInfo(equipmentseice.queryList(dto)));
//        PageHelper.startPage(dto.getPage(), dto.getPageSize(), dto.getOrderBy());
        List<EquipmentBean> list = ADOConnection.runTask(getCurrDs(), equipmentrunservice, "queryList", List.class, dto);
        return Response.ok(list);
    }

    @ApiOperation(value = "基础信息维护-列表")
    @GetMapping("/queryBaseList")
    public Response<PageInfo> queryBaseList(EquipmentDto dto) {
//        return Response.ok(new PageInfo(equipmentseice.queryList(dto)));
        PageHelper.startPage(dto.getPage(), dto.getPageSize(), dto.getOrderBy());
        List<EquipmentBean> list = ADOConnection.runTask(getCurrDs(), equipmentrunservice, "queryList", List.class, dto);
        return Response.ok(new PageInfo(list));
    }

    /**
     * @param deptManage                排序记录id
     * @param targetDeptManage          目标排序记录id
     * @param sort                      排序记录sort
     * @return
     */
    @ApiOperation(value = "单位顺序交换")
    @GetMapping("/deptMangeSortSwap")
    public Response deptMangeSortSwap(@RequestParam("deptManage") String deptManage, @RequestParam("targetDeptManage") String targetDeptManage,
                                         @RequestParam(value = "sort", required = false) String sort) {
        // 排序记录sort为null,从0开始按最大序号初始化
        if (ObjectUtil.isNull(sort)) {
            Boolean flag = ADOConnection.runTask(getCurrDs(), factory -> {
                EquipmentDeMapper mapper = factory.getMapper(EquipmentDeMapper.class);
                // 找出现有排序的记录
                List<EquipmentBean> existlist = mapper.queryDeptManageAndDeptManageNameAndDeptSortByDeptSortIsNotNull();
                int psort = 0;
                if (CollUtil.isNotEmpty(existlist)) {
                    psort = existlist.stream().filter(p -> p.getDeptSort() != null).map(EquipmentBean::getDeptSort).sorted((a1, a2) -> a2.compareTo(a1)).findFirst().get();
                }
                // 找出没有排序的记录
                List<EquipmentBean> sortnulllist = mapper.queryDeptManageAndDeptManageNameAndDeptSortByDeptSortIsNull();
                String deptMange = "";
                for (EquipmentBean waitsort : sortnulllist) {
                    Optional<EquipmentBean> any = existlist.stream().filter(e -> e.getDeptManage().equals(waitsort.getDeptManage())).findAny();
                    if (any.isPresent()) {
                        waitsort.setDeptSort(any.get().getDeptSort());
                    } else {
                        if (!StrUtil.equals(deptMange, waitsort.getDeptManage())) {
                            psort = psort + 1;
                            deptMange = waitsort.getDeptManage();
                        }
                        waitsort.setDeptSort(psort);
                    }
                    // 数据不多，逐条更新
                    mapper.updateDeptSortByDeptManage(waitsort.getDeptSort(), waitsort.getDeptManage());
                }
                return true;
            }, Boolean.class);
        }
        Assert.isFalse(StrUtil.isBlank(targetDeptManage), "目标不能为空");
        Boolean flag = ADOConnection.runTask(getCurrDs(), factory -> {
            EquipmentDeMapper mapper = factory.getMapper(EquipmentDeMapper.class);
            List<EquipmentBean> equipmentBeans = mapper.queryByDeptManageIn(CollUtil.newArrayList(deptManage, targetDeptManage));
            Assert.isFalse(ObjectUtil.hasEmpty(equipmentBeans.get(0).getDeptSort(), equipmentBeans.get(1).getDeptSort()), "移动记录或目标记录排序号为空");

            // 交换排序号
            Integer middleDeptSort = equipmentBeans.get(0).getDeptSort();
            equipmentBeans.get(0).setDeptSort(equipmentBeans.get(1).getDeptSort());
            equipmentBeans.get(1).setDeptSort(middleDeptSort);

            mapper.updateDeptSortByDeptManage(equipmentBeans.get(0).getDeptSort(), equipmentBeans.get(0).getDeptManage());
            mapper.updateDeptSortByDeptManage(equipmentBeans.get(1).getDeptSort(), equipmentBeans.get(1).getDeptManage());
            return true;
        }, Boolean.class);

        return Response.ok();
    }

    /**
     * @param id            排序记录id
     * @param target        目标排序记录id
     * @param sort          排序记录sort
     * @param equipmentType 主要设备类型
     * @return
     */
    @ApiOperation(value = "设备顺序交换")
    @GetMapping("/sortSwap")
    public Response sortSwap(@RequestParam("id") String id, @RequestParam("target") String target,
                                @RequestParam(value = "sort", required = false) String sort, @RequestParam("equipmentType") String equipmentType) {
        // 排序记录sort为null,从0开始按最大序号初始化
        if (ObjectUtil.isNull(sort)) {
            Boolean flag = ADOConnection.runTask(getCurrDs(), factory -> {
                EquipmentDeMapper mapper = factory.getMapper(EquipmentDeMapper.class);
                EquipmentBean equipmentBean = mapper.queryFirstByEquipmentId(id);
                // 找出现有排序的记录
                List<EquipmentBean> existlist = mapper.queryByEquipmentTypeAndSortNotNull(equipmentType, equipmentBean.getDeptManage());
                int psort = 0;
                if (CollUtil.isNotEmpty(existlist)) {
                    psort= existlist.stream().filter(p -> p.getSort() != null).map(EquipmentBean::getSort).sorted((a1, a2) -> a2.compareTo(a1)).findFirst().get();
                }
                // 找出没有排序的记录
                List<EquipmentBean> sortnulllist = mapper.queryByEquipmentTypeAndSortIsNull(equipmentType, equipmentBean.getDeptManage());
                for (EquipmentBean waitsort : sortnulllist) {
                    psort = psort + 1;
                    waitsort.setSort(psort);
                    // 数据不多，逐条更新
                    mapper.updateSortByEquipmentId(psort, waitsort.getEquipmentId());
                }
                return true;
            }, Boolean.class);
        }
        Assert.isFalse(StrUtil.isBlank(target), "目标不能为空");
        Boolean flag = ADOConnection.runTask(getCurrDs(), factory -> {
            EquipmentDeMapper mapper = factory.getMapper(EquipmentDeMapper.class);
            List<EquipmentBean> equipmentBeans = mapper.queryByEquipmentIdIn(CollUtil.newArrayList(id, target));
            long count = equipmentBeans.stream().map(EquipmentBean::getDeptManage).distinct().count();
            Assert.isFalse(count >= 2, "不能跨单位移动");
            Assert.isFalse(ObjectUtil.hasEmpty(equipmentBeans.get(0).getSort(), equipmentBeans.get(1).getSort()), "移动记录或目标记录排序号为空");

            // 交换排序号
            Integer middleSort = equipmentBeans.get(0).getSort();
            equipmentBeans.get(0).setSort(equipmentBeans.get(1).getSort());
            equipmentBeans.get(1).setSort(middleSort);

            mapper.updateSortByEquipmentId(equipmentBeans.get(0).getSort(), equipmentBeans.get(0).getEquipmentId());
            mapper.updateSortByEquipmentId(equipmentBeans.get(1).getSort(), equipmentBeans.get(1).getEquipmentId());
            return true;
        }, Boolean.class);

        return Response.ok();
    }

    @ApiOperation(value = "调度-设备管理单位")
    @GetMapping("/queryDispatchAlldept")
    public Response<List<DispatchDeptBean>> queryDispatchAlldept() {
        List<DispatchDeptBean> list = ADOConnection.runTask(getCurrDs(), factory -> {
            return factory.getMapper(EquipmentDeMapper.class).queryAllDispatchDept();
        }, List.class);
        return Response.ok(list);
    }


    @ApiOperation(value = "状态录入-列表")
    @GetMapping("/queryStatusList")
    public Response<PageInfo> queryStatusList(HistoryListDto dto) {
        if (CollUtil.isEmpty(dto.getOrders())) {
            ArrayList<OrderItem> orderItems = Lists.newArrayList(new OrderItem("deptSort", true), new OrderItem("sort", true));
            dto.setOrders(orderItems);
        }
        PageHelper.startPage(dto.getPage(), dto.getPageSize(), dto.getOrderBy());
        List<HistoryListDto> list = ADOConnection.runTask(getCurrDs(), equipmentrunservice, "queryStatusList", List.class, dto);
        return Response.ok(new PageInfo(list));
    }

    @ApiOperation(value = "状态录入-变更历史-列表")
    @GetMapping("/queryOldStatusList")
    public Response<PageInfo> queryOldStatusList(HistoryListDto dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize(), dto.getOrderBy());
        List<HistoryListDto> list = ADOConnection.runTask(getCurrDs(), equipmentrunservice, "queryStatusHistoryList", List.class, dto);
        return Response.ok(new PageInfo(list));
    }


    @ApiOperation(value = "事故跳闸-列表")
    @GetMapping("/queryAccidentList")
    public Response<PageInfo> queryAccidentList(AccidentDto dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize(), dto.getOrderBy());
        List<EquipmentAccidentBean> list = ADOConnection.runTask(getCurrDs(), equipmentrunservice, "queryAccidentList", List.class, dto);
        list.stream().forEach(b -> {
            b.setDuration(DateUtil.between(b.getStartTime(), b.getEndTime(), DateUnit.HOUR));
        });
        return Response.ok(new PageInfo(list));
    }

    @ApiOperation(value = "线路管理-公司驾驶舱")
    @GetMapping("/queryAccidentListQty")
    public Response<LineCockpitVo> queryAccidentListQty() {
        Integer qty = ADOConnection.runTask(getCurrDs(), factory -> {
            AccidentDto dto = new AccidentDto();
            dto.setStartTime(DateUtil.beginOfYear(new Date()));
            dto.setEndTime(DateUtil.endOfYear(new Date()));
            List<EquipmentAccidentBean> templist = factory.getMapper(EquipmentAccidentMapper.class).queryByAll(dto);
            return templist.size();
        }, Integer.class);
        LineCockpitVo lineCockpitVo = new LineCockpitVo();
        lineCockpitVo.setTzQty(qty);
        lineCockpitVo.setPfQty(0);
        lineCockpitVo.setSgQty(0);

        return Response.ok(lineCockpitVo);
    }

    @ApiOperation(value = "状态录入-状态变更")
    @GetMapping("/changeStatus")
    public Response changeStatus(ChangeStatusDto dto) {
        log.info("接收到参数：" + FastJsonUtils.getBeanToJson(dto));
        log.info("接收到参数：" + FastJsonUtils.getBeanToJson(dto));
        CommonChangStats(dto);
        return Response.ok();
    }

    @ApiOperation(value = "状态录入-状态变更(检修申请变更状态入口)")
    @GetMapping("/changeStatusOverhaul")
    public Response changeStatusOverhaul(ChangeStatusDto dto) {
        log.info("接收到参数：" + FastJsonUtils.getBeanToJson(dto));
        log.info("接收到参数：" + FastJsonUtils.getBeanToJson(dto));
        EquipmentBaseBean checkbean = ADOConnection.runTask(getCurrDs(), factory -> {
            return factory.getMapper(EquipmentDeMapper.class).queryFirstByEquipmentId(dto.getEquipmentId());
        }, EquipmentBaseBean.class);
        if (ObjectUtil.isNotNull(checkbean)) {
            CommonChangStats(dto);
        } else {
            Response.ok("该设备不属于调度设备");
        }
        return Response.ok();
    }

    /**
     * 1、调度设备状态变更
     * 2、检修申请单变更状态
     *
     * @param dto
     */
    private void CommonChangStats(ChangeStatusDto dto) {
        EquipmentHistoryBean oldbean = ADOConnection.runTask(getCurrDs(), factory -> {
            EquipmentHistoryBean bean = factory.getMapper(EquipmentHistoryMapper.class).queryMaxChangeIimeFirstByEquipmentId(dto.getEquipmentId());
            return bean;
        }, EquipmentHistoryBean.class);


        if (StringUtils.isNotNull(oldbean)) {
            Assert.isFalse(oldbean.getAfterStatus() == dto.getStatus(), "当前状态已是经变更状态");
            Assert.isFalse(DateUtil.between(oldbean.getChangeTime(), dto.getChangeTime(), DateUnit.SECOND, false) <= 0, "变更时间不能少于等于上次变更时间");
        }

        EquipmentHistoryBean bean = new EquipmentHistoryBean();
        bean.setEquipmentId(dto.getEquipmentId());
        bean.setContent(dto.getContent());
        bean.setBusinessId(dto.getBusinessId());  //检修单id
        bean.setBusinessStatus(dto.getBusinessStatus());    //检修单类型
        bean.setAfterStatus(dto.getStatus());
        bean.setChangeTime(dto.getChangeTime());
        bean.setChangeMan(getCurrUser().getAccount());
        bean.setChangeManName(getCurrUser().getName());

        if (StringUtils.isNotNull(oldbean)) {
            bean.setBeforeChangeTime(oldbean.getChangeTime());
            bean.setBeforeStatus(oldbean.getAfterStatus());
        } else {
            bean.setBeforeStatus(OverhaulStatusEnum.AVA.getValue());//如果没有历史记录，把变更前记录改为可用
        }
        ADOConnection.runTask(getCurrDs(), equipmentrunservice, "changeStatus", Integer.class, bean);
    }


    @ApiOperation(value = "事故跳闸-新建\\保存")
    @PostMapping("/saveAccident")
    public Response<String> saveAccident(@RequestBody EquipmentAccidentBean bean) {
        String id = ADOConnection.runTask(getCurrDs(), equipmentrunservice, "saveAccident", String.class, bean);
        return Response.ok(id);
    }


    @ApiOperation(value = "事故跳闸-详情")
    @GetMapping("/detailsAccident")
    public Response<EquipmentAccidentBean> detailsAccident(@RequestParam("id") String id) {
        EquipmentAccidentBean result = ADOConnection.runTask(getCurrDs(), factory -> {
            EquipmentAccidentBean bean = factory.getMapper(EquipmentAccidentMapper.class).selectByPrimaryKey(id);
            List<AffectedLineBean> affectedLineBeans = factory.getMapper(AffectedLineMapper.class).queryAllByAccidentId(id);
            bean.setDet(affectedLineBeans);
            bean.setDetstr(affectedLineBeans.stream().map(AffectedLineBean::getEquipmentName).collect(Collectors.joining(",")));
            bean.setDeptName(bean.getDeptManageName());//复制
            bean.setDeptId(bean.getDeptManage());//复制
            return bean;
        }, EquipmentAccidentBean.class);
        return Response.ok(result);
    }


    @ApiOperation(value = "事故跳闸-删除")
    @DeleteMapping("/deleteAccident")
    public Response deleteAccident(@RequestParam("id") String id) {
        ADOConnection.runTask(getCurrDs(), factory -> {
            return factory.getMapper(EquipmentAccidentMapper.class).deleteById(id);
        }, Integer.class);
        return Response.ok();
    }


    @ApiOperation(value = "获取监控数据库开关机记录")
    @GetMapping("/synStartLog")
    public Response synStartLog() {

        //系统库
        List<UnitRelationDo> unitrelist = ADOConnection.runTask(factory -> {
            ConfigTypeMapper configTypeMapper = factory.getMapper(ConfigTypeMapper.class);
            EquipmentDeMapper equipmentdemapper = factory.getMapper(EquipmentDeMapper.class);
            // 获取配置项id
            String detailId = configTypeMapper.getByClassifyCodeAndCode("operation", "unit_relation").getId();
            // 根据配置id 和 租户appid 查出 机组对应关系
            ConfigDetailQuery configDetailQuery = new ConfigDetailQuery(detailId, getCurrUser().getAppId());
            // 所有泵张机组
            return equipmentdemapper.getUnitrelationlist(configDetailQuery);
        }, List.class);

        List<UnitSynDto> unitSynFilterlist = ADOConnection.runTask(getCurrDs(), equipmentrunservice, "getUnitStartLogParameter", List.class, unitrelist);

        //获取所有泵张的开停机记录
        Response<List<UnitSynDto>> responseMsg = monitorfeign.getUnitStartLog(unitSynFilterlist);
        Assert.isFalse(responseMsg.getCode() != 200, responseMsg.getDescription());
        if (responseMsg.getCode() == 200) {
            List<UnitSynDto> unitloglist = responseMsg.getData();//开停机记录
            List<StartLogBean> insertlist = new ArrayList();     //开关机插库模式
            //遍历不同泵站
            unitloglist.stream().forEach(a -> {
                if (CollUtil.isNotEmpty(a.getRecordlist())) {
                    List<TabPmpMonitor> distinct = a.getRecordlist().stream().distinct().collect(Collectors.toList());//去重
                    //遍历泵站下的同步数据
                    distinct.stream().forEach(di -> {
                        StartLogBean bean = new StartLogBean();
                        bean.setId(CodeTools.getCode32());
                        bean.setDeptManage(a.getDeptManage());
                        bean.setDeptManageName(a.getDeptManageName());
                        bean.setEquipmentId(a.getEquipmentId());
                        bean.setEquipmentName(a.getEquipmentName());
                        bean.setEquipmentType(EquipmentEnum.UNIT.getValue());
                        bean.setOperateTime(DateUtil.parse(di.getLastsyntime()));//同步时间
                        bean.setOperateType(StarLogUntil.ConverOperType(di.getOper()));//转换成eam类型
                        bean.setContent(di.getDescription());//原因
                        bean.setIsConfirm(0);   // 默认是待确认
                        bean.setDataSource(StrUtil.format("{}-{}", "syn", DateUtil.format(new Date(), "yyyy-MM-dd hh:mm:ss")));
                        insertlist.add(bean);
                    });
                }
            });
            ADOConnection.runTask(getCurrDs(), startlogservice, "bathInsert", Void.class, insertlist);
        }

        return Response.ok();
    }

    private List<EquipmentBean> getEquipments(String result) {
        List<EquipmentBean> synlist = new ArrayList<>();//同步数据
        try {
            Response response = deviceservice.getParamsByResult(result);
            if (response.getCode() == 200) {
                String beanToJson = FastJsonUtils.getBeanToJson(response.getData());
                log.info(StrUtil.format("远程调用台账数据：{}", beanToJson));
                List<EquipmentSynDto> jsonToList = FastJsonUtils.getJsonToList(beanToJson, EquipmentSynDto.class);
                for (EquipmentSynDto s : jsonToList) {
                    EquipmentBean bean = new EquipmentBean();
                    List<EquipmentParamsSynDto> params = s.getParams();
                    if (StringUtils.isNotEmpty(params)) {
                        Predicate<EquipmentParamsSynDto> preOn = ben -> StrUtil.contains(ben.getParamName(), "管理部门");
                        Predicate<EquipmentParamsSynDto> pretwo = ben -> StrUtil.contains(ben.getParamName(), "设备管理单位");
                        Optional<EquipmentParamsSynDto> first = params.stream().filter(preOn.or(pretwo)).findFirst();
                        if (first.isPresent()) {
                            // 设置设备管理单位
                            bean.setDeptManage(first.get().getParamResult());
                            bean.setDeptManageName(first.get().getParamValue());
                        } else {
                            continue;   //台账接口的提供的设备数据，没有设备管理单位和管理部门 的设备不属于 主要设备
                        }

                        // 设置投运日期
                        Optional<EquipmentParamsSynDto> optStartUser = params.stream().filter(p -> p.getParamName().equals("投运日期")).findFirst();
                        if (optStartUser.isPresent()) {
                            bean.setStartUse(DateUtil.parse(optStartUser.get().getParamValue()));
                        }
                        // 设置当前运行状态
                        Optional<EquipmentParamsSynDto> optRunningState = params.stream().filter(p -> p.getParamName().equals("当前状态")).findFirst();
                        if (optRunningState.isPresent()) {
                            bean.setRunningState(optRunningState.get().getParamResult());
                        }
                    }

//                     解析返回json中 fullPathCode、fullPathName，找到设备所在部门
                    if (s.getFullPathName().contains("部")) {
                        List<String> deptIds = StrUtil.split(s.getFullPathCode(), "/");
                        List<String> deptNames = StrUtil.split(s.getFullPathName(), "/");
                        int index = CollUtil.lastIndexOf(deptNames, s1 -> {
                            return s1.contains("部");
                        });
                        bean.setDeptId(deptIds.get(index));            //设置部门id
                        bean.setDeptName(deptNames.get(index));  //设置部门名称
                    }

                    bean.setEquipmentId(s.getId());
                    bean.setEquipmentName(s.getName());
                    bean.setEquipmentType(result);
                    bean.setLastSynTime(DateUtil.now());
                    synlist.add(bean);
                }
            }
        } finally {
            latch.countDown();
            ThreadLocalContext.clear();
        }
        return synlist;
    }
}
